package com.molichuxing.gateway.bff.order.services.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

import javax.annotation.Resource;

import com.molichuxing.services.business.dto.request.modify.StockCarRejectionBizModifyDto;
import com.molichuxing.services.infrastructure.dto.request.create.*;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.dto.TabDto;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.DingTalkUtil;
import com.molichuxing.framework.utils.EmailUtil;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.framework.utils.SnowflakeUtil;
import com.molichuxing.gateway.bff.order.entity.request.create.ContractPathVo;
import com.molichuxing.gateway.bff.order.entity.request.create.OrderDealerCreateVo;
import com.molichuxing.gateway.bff.order.entity.request.create.OrderDealerDeliveryCreateVo;
import com.molichuxing.gateway.bff.order.entity.request.modify.OrderDealerCarChangeVinModifyVo;
import com.molichuxing.gateway.bff.order.entity.request.modify.OrderDealerDispatcherModifyVo;
import com.molichuxing.gateway.bff.order.entity.request.modify.OrderDeliverySlipModifyVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerCarInfoVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerCarVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerContractVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerDetailBasicInfoVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerDetailBasicVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerDetailCarInfoVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerDetailScheduleVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerDetailStartVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerDetailStatusVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerDetailVehicleVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderDealerVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderFuzzyQueryVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderScheduleUnpaidVo;
import com.molichuxing.gateway.bff.order.services.OrderDealerBffService;
import com.molichuxing.gateway.property.EmailSubjectEnum;
import com.molichuxing.gateway.property.EmailTemplateEnum;
import com.molichuxing.gateway.utils.TokenUtil;
import com.molichuxing.gateway.utils.entity.UserEntity;
import com.molichuxing.services.business.dto.request.create.ContractImageBizCreateDto;
import com.molichuxing.services.business.dto.request.create.ContractPurchaseBizCreateDto;
import com.molichuxing.services.business.dto.request.modify.StockCarBizModifyDto;
import com.molichuxing.services.business.dto.response.ContractImageBizDto;
import com.molichuxing.services.business.dto.response.ContractPurchaseBizDto;
import com.molichuxing.services.business.dto.response.OfflineBizDto;
import com.molichuxing.services.business.dto.response.OrderDealerBizDto;
import com.molichuxing.services.business.dto.response.OrderDealerDeliveryBizDto;
import com.molichuxing.services.business.dto.response.OrderDealerDetailBasicBizDto;
import com.molichuxing.services.business.dto.response.OrderDealerDetailCarInfoBizDto;
import com.molichuxing.services.business.dto.response.OrderDealerDetailStartBizDto;
import com.molichuxing.services.business.service.ContractBizService;
import com.molichuxing.services.business.service.OfflineBizService;
import com.molichuxing.services.business.service.OrderDealerBizService;
import com.molichuxing.services.business.service.OrderScheduleBizService;
import com.molichuxing.services.business.service.OrderTradeFlowBizService;
import com.molichuxing.services.business.service.StockCarBizService;
import com.molichuxing.services.business.service.VehicleBizService;
import com.molichuxing.services.infrastructure.dto.request.modify.DeliverySlipModifyDto;
import com.molichuxing.services.infrastructure.dto.request.modify.IovFenceBindingModifyDto;
import com.molichuxing.services.infrastructure.dto.request.modify.OrderDealerStartStatusModifyDto;
import com.molichuxing.services.infrastructure.dto.request.modify.RefuseModifyFto;
import com.molichuxing.services.property.CarsOperateStatusEnum;
import com.molichuxing.services.property.CarsTypeEnum;
import com.molichuxing.services.property.OfflineAuditStatusEnum;
import com.molichuxing.services.property.OrderDealerScheduleOverdueEnum;
import com.molichuxing.services.property.OrderDealerSendCarStatusEnum;
import com.molichuxing.services.property.OrderDealerStatusEnum;
import com.molichuxing.services.property.OrderRequestTypeEnum;
import com.molichuxing.services.property.OrderScheduleStatusEnum;
import com.molichuxing.services.property.OrderTypeEnum;
import com.molichuxing.services.property.RiskEmailReceiveTypeEnum;
import com.molichuxing.services.property.RiskEmailTypeEnum;
import com.molichuxing.services.property.StockCarStatusEnum;
import com.molichuxing.services.property.StockCarStockTypeEnum;
import com.molichuxing.services.property.StockCarTypeEnum;

/**
 * @Author: renzhengyu
 * @Description:
 * @Date: Created in 10:34 2019/8/22
 * @Modified By:
 **/
@Service("orderDealerBffService")
public class OrderDealerBffServiceImpl implements OrderDealerBffService {
    private static final Logger logger = LoggerFactory.getLogger(OrderDealerBffServiceImpl.class);

    @Value("${email_account}")
    private String EMAIL_ACCOUNT;

    @Value("${email_password}")
    private String EMAIL_PASSWORD;

    @Value("${order.dealer.change.url}")
    private String ORDER_DEALER_CHANGE_URL;


    @Resource
    private OrderDealerBizService orderDealerBizService;

    @Resource
    private OrderDealerService orderDealerService;

    @Resource
    private OrderScheduleService orderScheduleService;

    @Resource
    private OrderDealerDeliveryService orderDealerDeliveryService;

    @Resource
    private OrderStatusFlowService orderStatusFlowService;

    @Resource
    private OrderDealerChangeCarsLogService orderDealerChangeCarsLogService;

    @Resource
    private OrderTradeFlowBizService orderTradeFlowBizService;

    @Resource
    private CarService carService;

    @Resource
    private VehicleBizService vehicleBizService;

    @Resource
    private VehicleColorService vehicleColorService;

    @Resource
    private SubcompanyService subcompanyService;

    @Resource
    private DealerService dealerService;

    @Resource
    private DealerDetailService dealerDetailService;

    @Resource
    private OfflineBizService offlineBizService;

    @Resource
    private StoreDetailService storeDetailService;

    @Resource
    private StockCarBizService stockCarBizService;

    @Resource
    private StockStoreService stockStoreService;

    @Resource
    private OrderScheduleBizService orderScheduleBizService;

    @Resource
    private StockCarService stockCarService;

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private ContractBizService contractBizService;

    @Resource
    private IovCarService iovCarService;

    @Resource
    private OrderService orderService;

    @Resource
    private IovFenceService iovFenceService;

    @Resource
    private EntrepotStorageService entrepotStorageService;

    @Resource
    private RiskEmailService riskEmailService;

    @Resource
    private CarFenceExceptionService carFenceExceptionService;


    @Override
    public Paged<OrderDealerVo> orderDealerList(Map<String, Object> params, Integer pageNum, Integer pageSize) throws Exception {
        Paged<OrderDealerVo> orderDealerVoPage = new Paged<>(null, 0, pageSize);

        if(null !=params.get("dealerName")){
            List<Integer> dealerIds = new ArrayList<>();
            List<DealerDto> dealerDtoList = dealerService.getAllDealerListByName(String.valueOf(params.get("dealerName")));
            if(null != dealerDtoList  && dealerDtoList.size()> 0){
                for (DealerDto dealerDto:dealerDtoList) {
                    dealerIds.add(dealerDto.getDealerId());
                }
            }else{
                dealerIds.add(0);
            }
            params.put("dealerIds",dealerIds);
        }
        Paged<OrderDealerBizDto> orderDealerBizDtoPage = orderDealerBizService.getOrderDealerBusList(params, pageNum, pageSize, OrderRequestTypeEnum.OP);
        if (null == orderDealerBizDtoPage) {
            return orderDealerVoPage;
        }
        BeanUtils.copyProperties(orderDealerBizDtoPage, orderDealerVoPage);
        if (null == orderDealerBizDtoPage.getList()) {
            return orderDealerVoPage;
        }
        List<OrderDealerVo> orderDealerVoList = new ArrayList<>();
        OrderDealerVo orderDealerVo = null;
        List<OrderDealerCarVo> carInfoList = null;
        String vehicleName;
        for (OrderDealerBizDto orderDealerBizDto : orderDealerBizDtoPage.getList()) {
            orderDealerVo = new OrderDealerVo();
            BeanUtils.copyProperties(orderDealerBizDto, orderDealerVo);
            orderDealerVo.setOrderStatusName(OrderDealerStatusEnum.getName(orderDealerBizDto.getOrderStatus()));
			orderDealerVo.setOrderCode(orderDealerBizDto.getOrderCode());
			//总金额=总保证金+总租金
            orderDealerVo.setRentAmount(orderDealerBizDto.getRentAmount().add(orderDealerBizDto.getDepositAmount()));
            DealerDto dealerDto = dealerService.getDealerById(orderDealerBizDto.getDealerId());
            if(null == dealerDto){
                throw new Exception("非法入参");
            }
            orderDealerVo.setDealerName(dealerDto.getShortName());
            //查询车辆信息
            carInfoList =new ArrayList<>();
            OrderDealerCarVo orderDealerCarVo = null;
            for (Integer carId:orderDealerVo.getCarIdList()) {
                orderDealerCarVo = new OrderDealerCarVo();
                //获取车辆基础信息
                CarDto carDto = carService.getCarById(carId);
                if(null == carDto){
                    throw new Exception("非法入参");
                }
                //获取车型名称
                vehicleName = vehicleBizService.getVehicleName(carDto.getVehicleId());
                if(null == vehicleName){
                    throw new Exception("非法入参");
                }
                orderDealerCarVo.setLicencePlate(carDto.getLicencePlate());
                orderDealerCarVo.setVin(carDto.getVin());
                orderDealerCarVo.setVehicleName(vehicleName);
                carInfoList.add(orderDealerCarVo);
            }
            orderDealerVo.setCarInfoList(carInfoList);
            orderDealerVoList.add(orderDealerVo);
        }
        orderDealerVoPage.setList(orderDealerVoList);
        return orderDealerVoPage;
    }


    @Override
    public List<OrderDealerDetailStatusVo> getDealerOrderFlow(Long orderCode) throws Exception {
        List<OrderDealerDetailStatusVo> orderDealerDetailStatusVoList = null;
        List<OrderDealerDetailStatusDto> orderDealerDetailStatusDtoList = orderStatusFlowService.getOrderDealerDetailStausFlowList(orderCode);
        if(null == orderDealerDetailStatusDtoList || orderDealerDetailStatusDtoList.size() <= 0){
            throw new Exception("非法入参");
        }
        orderDealerDetailStatusVoList = new ArrayList<>();
        OrderDealerDetailStatusVo orderDealerDetailStatusVo = null;
        for (OrderDealerDetailStatusDto orderDealerDetailStatusDto:
                orderDealerDetailStatusDtoList) {
            orderDealerDetailStatusVo =new OrderDealerDetailStatusVo();
            orderDealerDetailStatusVo.setOrderStatus(orderDealerDetailStatusDto.getOrderStatus().getName());
            orderDealerDetailStatusVo.setGmtCreate(orderDealerDetailStatusDto.getGmtCreate());
            orderDealerDetailStatusVoList.add(orderDealerDetailStatusVo);
        }
        return orderDealerDetailStatusVoList;
    }



    @Override
    public OrderDealerDetailBasicVo orderDetailBasic(Long orderCode) throws Exception {
        OrderDealerDetailBasicVo  orderDealerDetailBasicVo= null;
        //查询采购单基础信息详情
        OrderDealerDetailBasicDto orderDealerDetailBasicDto = orderDealerService.getDetailBasic(orderCode);
        if (null == orderDealerDetailBasicDto) {
            throw new Exception("非法入参");
        }
        orderDealerDetailBasicVo= new OrderDealerDetailBasicVo();
        BeanUtils.copyProperties(orderDealerDetailBasicDto,orderDealerDetailBasicVo);

        DealerDto dealerDto = dealerService.getDealerById(orderDealerDetailBasicDto.getDealerId());
        if(null == dealerDto){
            throw new Exception("无经销商名称信息");
        }
        orderDealerDetailBasicVo.setDealerName(dealerDto.getShortName());
        DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(orderDealerDetailBasicDto.getDealerId());
        if(null == dealerDetailDto){
            throw new Exception("无联系人信息");
        }
        orderDealerDetailBasicVo.setContact(dealerDetailDto.getResponsibleName());
        orderDealerDetailBasicVo.setContactNumber(dealerDetailDto.getResponsiblePhone());

        // 获取采购单合同信息  入参：订单号       出参：[合同名称，合同地址]
        ContractPurchaseBizDto contractPurchaseBizDto = contractBizService.getPurchaseContract(orderCode);
        if(null != contractPurchaseBizDto && null != contractPurchaseBizDto.getList() && contractPurchaseBizDto.getList().size() > 0){
            List<OrderDealerContractVo> contractList = new ArrayList<>();
            OrderDealerContractVo orderDealerContractVo = null;
            for (ContractImageBizDto contractImageBizDto:contractPurchaseBizDto.getList()) {
                orderDealerContractVo = new OrderDealerContractVo();
                orderDealerContractVo.setContractName(contractImageBizDto.getName());
                orderDealerContractVo.setContractUrl(contractImageBizDto.getPath());
                contractList.add(orderDealerContractVo);
            }
            orderDealerDetailBasicVo.setContractList(contractList);
        }

        SubcompanyDto subcompanyDto = subcompanyService.getSubcompanyNameById(orderDealerDetailBasicDto.getSubCompanyId());
        if(null == subcompanyDto){
            throw new Exception("非法入参");
        }
        orderDealerDetailBasicVo.setSubCompanyName(subcompanyDto.getName());

        return orderDealerDetailBasicVo;
    }

    @Override
    public OrderDealerDetailVehicleVo orderDetailVehicle(Long orderCode) throws Exception {
        OrderDealerDetailVehicleVo orderDealerDetailVehicleVo = null;
        //查询车辆信息和发车信息
        OrderDealerDeliveryBizDto orderDealerDeliveryBizDto = orderDealerBizService.getOrderDetailCarsInfo(orderCode);
        if (null == orderDealerDeliveryBizDto || null == orderDealerDeliveryBizDto.getOrderDealerDetailCarInfoList() || orderDealerDeliveryBizDto.getOrderDealerDetailCarInfoList().size() <= 0 ) {
            throw new Exception("非法入参");
        }
        orderDealerDetailVehicleVo = new OrderDealerDetailVehicleVo();
        List<OrderDealerDetailCarInfoVo> orderDealerDetailCarInfoVoList = new ArrayList<>();
        OrderDealerDetailCarInfoVo orderDealerDetailCarInfoVo = null;
        String vehicleName = null;
        //总租金
        BigDecimal sumRent = new BigDecimal("0");
        //总保证金
        BigDecimal sumDeposit = new BigDecimal("0");
        Map<Integer,Integer> vehicleTypeCount = new HashMap<>();
        Integer carCount;
        for (OrderDealerDetailCarInfoBizDto orderDealerDetailCarInfoBizDto:orderDealerDeliveryBizDto.getOrderDealerDetailCarInfoList()) {
            orderDealerDetailCarInfoVo =new OrderDealerDetailCarInfoVo();
            BeanUtils.copyProperties(orderDealerDetailCarInfoBizDto,orderDealerDetailCarInfoVo);
            //获取车辆基础信息
            CarDto carDto = carService.getCarById(orderDealerDetailCarInfoBizDto.getCarId());
            if(null == carDto){
                throw new Exception("非法入参");
            }
            //获取车型名称
            vehicleName = vehicleBizService.getVehicleName(carDto.getVehicleId());
            if(null == vehicleName){
                throw new Exception("非法入参");
            }
            //获取车身颜色
            VehicleColorDto vehicleColorDto = vehicleColorService.getVehicleColorByvehicleColorId(carDto.getVehicleColorId());
            if(null == vehicleColorDto){
                throw new Exception("非法入参");
            }
            orderDealerDetailCarInfoVo.setVehicleName(vehicleName);
            //计算车型对应的车辆数
            if(null == vehicleTypeCount.get(carDto.getVehicleId())){
                vehicleTypeCount.put(carDto.getVehicleId(),1);
            }else{
                carCount = vehicleTypeCount.get(carDto.getVehicleId());
                vehicleTypeCount.put(carDto.getVehicleId(),++carCount);
            }

            orderDealerDetailCarInfoVo.setVin(carDto.getVin());
            orderDealerDetailCarInfoVo.setVehicleId(carDto.getVehicleId());
            orderDealerDetailCarInfoVo.setLicencePlate(carDto.getLicencePlate());
            orderDealerDetailCarInfoVo.setVehicleColor(vehicleColorDto.getName());
            sumRent = sumRent.add(orderDealerDetailCarInfoBizDto.getRent());
            sumDeposit = sumDeposit.add(orderDealerDetailCarInfoBizDto.getDeposit());
            orderDealerDetailCarInfoVo.setDrivingMileage(orderDealerDetailCarInfoBizDto.getTotalMileage());
            orderDealerDetailCarInfoVoList.add(orderDealerDetailCarInfoVo);
        }

        List<OrderDealerDetailCarInfoVo> orderDealerCarCountVoList = new ArrayList<>();
        for (OrderDealerDetailCarInfoVo orderDealerCarCountVo:orderDealerDetailCarInfoVoList) {
            orderDealerCarCountVo.setCarCount(vehicleTypeCount.get(orderDealerCarCountVo.getVehicleId()));
            orderDealerCarCountVoList.add(orderDealerCarCountVo);
        }
        orderDealerDetailVehicleVo.setOrderDealerDetailCarInfoList(orderDealerCarCountVoList);
        orderDealerDetailVehicleVo.setSumRent(sumRent);
        orderDealerDetailVehicleVo.setSumDeposit(sumDeposit);

        if(null != orderDealerDeliveryBizDto.getOrderDealerDetailStartList() && orderDealerDeliveryBizDto.getOrderDealerDetailStartList().size() > 0){
            List<OrderDealerDetailStartVo> orderDealerDetailStartList = new ArrayList<>();
            OrderDealerDetailStartVo orderDealerDetailStartVo= null;
            for (OrderDealerDetailStartBizDto orderDealerDetailStartBizDto:orderDealerDeliveryBizDto.getOrderDealerDetailStartList()) {
                orderDealerDetailStartVo = new OrderDealerDetailStartVo();
                BeanUtils.copyProperties(orderDealerDetailStartBizDto,orderDealerDetailStartVo);
                //获取车辆基础信息
                CarDto carDto = carService.getCarById(orderDealerDetailStartVo.getCarId());
                if(null == carDto){
                    throw new Exception("非法入参");
                }
                //获取车型名称
                vehicleName = vehicleBizService.getVehicleName(carDto.getVehicleId());
                if(null == vehicleName){
                    throw new Exception("非法入参");
                }
                //获取车身颜色
                VehicleColorDto vehicleColorDto = vehicleColorService.getVehicleColorByvehicleColorId(carDto.getVehicleColorId());
                if(null == vehicleColorDto){
                    throw new Exception("非法入参");
                }
                orderDealerDetailStartVo.setVin(carDto.getVin());
                orderDealerDetailStartVo.setLicencePlate(carDto.getLicencePlate());
                orderDealerDetailStartVo.setVehicleColor(vehicleColorDto.getName());
                orderDealerDetailStartVo.setVehicleName(vehicleName);

                orderDealerDetailStartList.add(orderDealerDetailStartVo);
            }
            orderDealerDetailVehicleVo.setOrderDealerDetailStartList(orderDealerDetailStartList);

        }


        return orderDealerDetailVehicleVo;
    }

    @Override
    public List<OrderDealerDetailScheduleVo> orderSchedule(Long orderCode) throws Exception {
        List<OrderDealerDetailScheduleVo> orderDealerDetailScheduleVoList = null;
        List<OrderScheduleDto> orderScheduleDtoList = orderScheduleService.getOrderSchedule(orderCode);
        if (null == orderScheduleDtoList || orderScheduleDtoList.size() <= 0) {
            throw new Exception("非法入参");
        }
        orderDealerDetailScheduleVoList = new ArrayList<>();
        OrderDealerDetailScheduleVo orderDealerDetailScheduleVo = null;
        Integer overdueDays = null;
        for (OrderScheduleDto orderScheduleDto : orderScheduleDtoList) {
            orderDealerDetailScheduleVo = new OrderDealerDetailScheduleVo();
            BeanUtils.copyProperties(orderScheduleDto,orderDealerDetailScheduleVo);
            orderDealerDetailScheduleVo.setStatus(orderScheduleDto.getStatus().getValue());
            orderDealerDetailScheduleVo.setStatusName(orderScheduleDto.getStatus().getName());
            if(null != orderScheduleDto.getPayWay()){
                orderDealerDetailScheduleVo.setPayWayStr(orderScheduleDto.getPayWay().getName());
            }
            if(!OrderScheduleStatusEnum.NO.equals(orderScheduleDto.getStatus())){
                // 获取还款流水信息   入参：订单号，还款id   出参：流水号
                OfflineBizDto offlineBizDto = offlineBizService.getOffline(orderScheduleDto.getOrderCode(),orderScheduleDto.getId());
                if (null == offlineBizDto ) {
                    throw new Exception("获取还款流水号信息为空");
                }
                orderDealerDetailScheduleVo.setSerialNumber(offlineBizDto.getSerialNumber());
            }
            //如果是第一期，不用处理逾期天数
            if(1 == orderDealerDetailScheduleVo.getPeriods()){
                orderDealerDetailScheduleVo.setPayableDate(null);
                orderDealerDetailScheduleVo.setIsOverdue("否");
                orderDealerDetailScheduleVo.setOverdueDays(0);
                orderDealerDetailScheduleVoList.add(orderDealerDetailScheduleVo);
                continue;
            }else{
                orderDealerDetailScheduleVo.setDeposit(null);
            }
            if(null != orderDealerDetailScheduleVo.getPayableDate()){

                    if(null != orderDealerDetailScheduleVo.getPaySuccessTime()){
                        //实际付款日期-应付款日期
                        overdueDays = (int)DateUtil.getDaysDiff(orderDealerDetailScheduleVo.getPayableDate() ,orderDealerDetailScheduleVo.getPaySuccessTime());
                        if(overdueDays < 0 ){
                            orderDealerDetailScheduleVo.setIsOverdue(OrderDealerScheduleOverdueEnum.NO_OVERDUE.getName());
                            orderDealerDetailScheduleVo.setOverdueDays(0);
                        }else{
                            orderDealerDetailScheduleVo.setIsOverdue(OrderDealerScheduleOverdueEnum.OVERDUE.getName());
                            orderDealerDetailScheduleVo.setOverdueDays(overdueDays);
                        }
                    }else {
                        //实际付款日期-应付款日期
                        overdueDays = (int)DateUtil.getDaysDiff(orderDealerDetailScheduleVo.getPayableDate() ,LocalDateTime.now());
                        if(overdueDays > 0 ){
                            orderDealerDetailScheduleVo.setIsOverdue(OrderDealerScheduleOverdueEnum.OVERDUE.getName());
                            orderDealerDetailScheduleVo.setOverdueDays(overdueDays);
                        }
                    }
            }
            orderDealerDetailScheduleVoList.add(orderDealerDetailScheduleVo);



        }

        return orderDealerDetailScheduleVoList;
    }

    @Override
    public Paged<OrderDealerDetailStartVo> orderDealerStartList(Long orderCode, Integer carStatus) throws Exception {
        Paged<OrderDealerDetailStartVo> orderDealerDetailStartVoPaged = new Paged<>();
        //脱敏要求total和pages不能为0
        orderDealerDetailStartVoPaged.setPages(1);
        orderDealerDetailStartVoPaged.setTotal(1);
        List<OrderDealerDetailStartVo> orderDealerDetailStartVoList = new ArrayList<>();
        List<TabDto> tabDto = orderDealerDeliveryService.getDetailStartCountDto(orderCode);
        if(null == tabDto){
            throw new Exception("非法入参");
        }
        orderDealerDetailStartVoPaged.setTab(tabDto);
        List<OrderDealerDetailStartDto> orderDealerDetailStartDtoList = orderDealerDeliveryService.getDetailStartDto(orderCode,carStatus);
        if(null == orderDealerDetailStartDtoList || orderDealerDetailStartDtoList.size() <= 0){
            return orderDealerDetailStartVoPaged;
        }
        OrderDealerDetailStartVo orderDealerDetailStartVo = null;
        String vehicleName = null;
        for (OrderDealerDetailStartDto orderDealerDetailStartDto: orderDealerDetailStartDtoList) {
            orderDealerDetailStartVo = new OrderDealerDetailStartVo();
            BeanUtils.copyProperties(orderDealerDetailStartDto,orderDealerDetailStartVo);
            //获取车辆基础信息
            CarDto carDto = carService.getCarById(orderDealerDetailStartDto.getCarId());
            if(null == carDto){
                throw new Exception("车辆基础信息为空");
            }
            orderDealerDetailStartVo.setCarId(orderDealerDetailStartDto.getCarId());
            orderDealerDetailStartVo.setVin(carDto.getVin());
            orderDealerDetailStartVo.setLicencePlate(carDto.getLicencePlate());
            //获取车型名称
            vehicleName = vehicleBizService.getVehicleName(carDto.getVehicleId());
            if(null == vehicleName){
                throw new Exception("车型信息为空");
            }
            orderDealerDetailStartVo.setVehicleName(vehicleName);

            //TODO 获取发车库id 多反一个名字字段
            StockCarDto stockCarDto = stockCarService.getStockCar(orderDealerDetailStartDto.getCarId());
            if(stockCarDto !=null && stockCarDto.getOutStockId() != null){
                orderDealerDetailStartVo.setOutStockId(stockCarDto.getOutStockId());
            }
            orderDealerDetailStartVoList.add(orderDealerDetailStartVo);
        }
        orderDealerDetailStartVoPaged.setList(orderDealerDetailStartVoList);
        return orderDealerDetailStartVoPaged;
    }

    @Override
    public Boolean orderDealerSendCar(OrderDealerDispatcherModifyVo orderDealerDispatcherModifyVo) throws Exception {
        //查询账号是否存在
        UserEntity currentLoginUser = tokenUtil.getUser();
        if(null == currentLoginUser){
            throw new Exception("用户未登录");
        }

        Integer status = orderDealerService.getOrderDealerStatus(orderDealerDispatcherModifyVo.getOrderCode());
        if(null == status ){
            throw new Exception("无效订单");
        }
        //是否安装tbox
        CarDto carDto = carService.getCarById(orderDealerDispatcherModifyVo.getCarId());
        if(null == carDto ){
            throw new Exception("车辆信息为空");
        }
        if(!carDto.getIsInstallTbox()) {
            throw new Exception("该车辆未安装tbox");
        }
        if(!status.equals(OrderDealerStatusEnum.WAIT_DEPARTURE.getValue()) && !status.equals(OrderDealerStatusEnum.WAIT_PICK_UP.getValue())){
            throw new Exception("当前状态不能发车");
        }
        //围栏异常校验
        StockCarDto stockCarDto = getStockCarDto(orderDealerDispatcherModifyVo.getCarId());

        // 调取车联网接口 根据车辆VIN 获取围栏id
        List<String> vinList = new ArrayList<>();
        vinList.add(orderDealerDispatcherModifyVo.getVin());
        Map<String, List<IovFenceDto>> fenceMap = iovFenceService.getFenceByVins(vinList);

        //判断车联网接口返回围栏信息是否为空
        if(fenceMap == null || fenceMap.get(orderDealerDispatcherModifyVo.getVin()) == null || fenceMap.get(orderDealerDispatcherModifyVo.getVin()).size() <= 0){
            //新增异常 “车辆为绑定仓储下的围栏”
            FenceExceptionCreateDto fenceExceptionCreateDto = new FenceExceptionCreateDto();
            fenceExceptionCreateDto.setCarId(orderDealerDispatcherModifyVo.getCarId());
            fenceExceptionCreateDto.setFenceId(stockCarDto.getFenceId());
            fenceExceptionCreateDto.setStockId(carDto.getStockId());
            fenceExceptionCreateDto.setType(carDto.getStockType());
            fenceExceptionCreateDto.setExplain("车辆为绑定仓储下的围栏");
            carFenceExceptionService.createCarFenceException(fenceExceptionCreateDto);
            throw new Exception("车辆为绑定仓储下的围栏");
        }
        Integer iovFenceId = fenceMap.get(orderDealerDispatcherModifyVo.getVin()).get(0).getId();
        // 判断围栏id是否一致
        if(!iovFenceId.equals(stockCarDto.getFenceId())){
            //新增异常 “车辆绑定仓储与车辆绑定围栏不符”
            FenceExceptionCreateDto fenceExceptionCreateDto = new FenceExceptionCreateDto();
            fenceExceptionCreateDto.setCarId(orderDealerDispatcherModifyVo.getCarId());
            fenceExceptionCreateDto.setFenceId(stockCarDto.getFenceId());
            fenceExceptionCreateDto.setStockId(carDto.getStockId());
            fenceExceptionCreateDto.setType(carDto.getStockType());
            fenceExceptionCreateDto.setExplain("车辆绑定仓储与车辆绑定围栏不符");
            carFenceExceptionService.createCarFenceException(fenceExceptionCreateDto);
            throw new Exception("车辆绑定仓储与车辆绑定围栏不符");
        }


        //解除中转库围栏
        modifyBindingFence(stockCarDto.getFenceId(),orderDealerDispatcherModifyVo.getVin());


        //车辆出库
        StockCarBizModifyDto stockCarBizModifyDto = new StockCarBizModifyDto();
        stockCarBizModifyDto.setCarId(orderDealerDispatcherModifyVo.getCarId());
        stockCarBizModifyDto.setStatus(StockCarStatusEnum.WAIT_STOCK.getValue());
        //根据门店id查库存id
        StockStoreDto stockStoreDto = stockStoreService.getStockStoreByStoreId(orderDealerDispatcherModifyVo.getOutStockId());
        if(null == stockStoreDto ){
            throw new Exception("库存id为空");
        }
        stockCarBizModifyDto.setStockId(stockStoreDto.getStockId());
        stockCarBizModifyDto.setStockType(StockCarStockTypeEnum.STORE.getValue());
        stockCarBizModifyDto.setStorageTime(LocalDateTime.now());
        stockCarBizModifyDto.setPdiUrl(orderDealerDispatcherModifyVo.getPdiUrl());
        stockCarBizModifyDto.setType(StockCarTypeEnum.ALLOT.getValue());
        // 获取登录用户信息  操作人id，操作人名称
        stockCarBizModifyDto.setAccountId(currentLoginUser.getAccountId());
        stockCarBizModifyDto.setAccountAccount(currentLoginUser.getRealName());
        stockCarBizModifyDto.setFenceId(orderDealerDispatcherModifyVo.getStockFenceId());
        stockCarBizService.modifyOutStock(stockCarBizModifyDto);


        //查询订单下所有发车状态
        List<Integer> sendStatusList =  orderDealerDeliveryService.getSendStatusByOrderCode(orderDealerDispatcherModifyVo.getOrderCode());
        if(null == sendStatusList || sendStatusList.size() <= 0){
            throw new Exception("非法入参");
        }
        int count = 0;
        for (Integer sendStatus: sendStatusList) {
            if(sendStatus == OrderDealerSendCarStatusEnum.NO_RECEIVED.getValue()){
                count++;
                continue;
            }
        }

        //如果是当前订单下第一次发车，则将采购单状态改为等待收车
        if(count == 0 ){
            Boolean modifyOrderStatus = orderDealerService.modifyOrderStatus(orderDealerDispatcherModifyVo.getOrderCode(), OrderDealerStatusEnum.WAIT_PICK_UP.getValue());

            OrderStatusFlowCreateDto orderStatusFlowCreateDto= new OrderStatusFlowCreateDto();
            orderStatusFlowCreateDto.setOrderCode(orderDealerDispatcherModifyVo.getOrderCode());
            orderStatusFlowCreateDto.setOrderStatus(OrderDealerStatusEnum.WAIT_PICK_UP.getValue());
            //获取登录用户信息  操作人id，操作人名称，操作人类型，
            orderStatusFlowCreateDto.setOrderUserId(currentLoginUser.getAccountId());
            orderStatusFlowCreateDto.setOrderModifiedType(currentLoginUser.getSystemType().getValue());
            orderStatusFlowCreateDto.setOrderUserName(currentLoginUser.getRealName());
            //订单流转状态插入
            Boolean createOrderStatusFlow =orderStatusFlowService.createOrderStatusFlow(orderStatusFlowCreateDto);
            if(!modifyOrderStatus || !createOrderStatusFlow){
                return false;
            }
        }

        //修改车辆的发车状态
        OrderDealerStartStatusModifyDto orderDealerStartStatusModifyDto = new OrderDealerStartStatusModifyDto();
        orderDealerStartStatusModifyDto.setCarId(orderDealerDispatcherModifyVo.getCarId());
        orderDealerStartStatusModifyDto.setOrderCode(orderDealerDispatcherModifyVo.getOrderCode());
        // 获取登录用户信息  操作人id，操作人名称
        orderDealerStartStatusModifyDto.setOperatorId(currentLoginUser.getAccountId());
        orderDealerStartStatusModifyDto.setOperatorName(currentLoginUser.getRealName());
        StoreDetailDto storeDetailDto = storeDetailService.getStoreDetailById(orderDealerDispatcherModifyVo.getOutStockId());
        if(null == storeDetailDto){
            throw new Exception("非法入参");
        }
        orderDealerStartStatusModifyDto.setStoreId(orderDealerDispatcherModifyVo.getOutStockId());
        orderDealerStartStatusModifyDto.setTakeAite(storeDetailDto.getAddress());
        orderDealerStartStatusModifyDto.setOutStockId(orderDealerDispatcherModifyVo.getInStockId());
        Boolean modifyCarStartStatus =  orderDealerDeliveryService.modifyCarStartStatus(orderDealerStartStatusModifyDto);
        if(!modifyCarStartStatus ){
            return false;
        }


        //查询订单信息
        OrderDealerDetailBasicDto orderDealerDetailBasicDto = orderDealerService.getDetailBasic(orderDealerDispatcherModifyVo.getOrderCode());

        //查询经销商简称
        DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(orderDealerDetailBasicDto.getDealerId());


        //邮件
        EmailUtil.sendMail(EMAIL_ACCOUNT, EMAIL_PASSWORD,
                EmailSubjectEnum.BUSINESS_PURCHASE_ORDER_DEPART.getName(),
                EmailTemplateEnum.BUSINESS_PURCHASE_ORDER_DEPART.getTemplate()
                        .replace("$【orderCode】", String.valueOf(orderDealerDispatcherModifyVo.getOrderCode()))
                        .replace("$【dateTime】", DateUtil.formatTime(LocalDateTime.now()))
                        .replace("$【licencePlate】", carDto.getLicencePlate()),
                dealerDetailDto.getEmail());

        return true;
    }

    @Override
    public Boolean orderDealerCarRefuse(Long orderCode, Integer carId, String rejectReason) throws Exception {

        Boolean ret = false;
        RefuseModifyFto refuseModifyFto = new RefuseModifyFto();
        refuseModifyFto.setCarId(carId);
        refuseModifyFto.setOrderCode(orderCode);
        refuseModifyFto.setRejectReason(rejectReason);

        ret = orderDealerDeliveryService.modifyCarRefuseStatus(refuseModifyFto);

        //查询车辆
        CarDto carDto = carService.getCarById(carId);
        //查询订单信息
        OrderDealerDetailBasicDto orderDealerDetailBasicDto = orderDealerService.getDetailBasic(orderCode);
        //查询经销商简称
        DealerDto dealerDto = dealerService.getDealerById(orderDealerDetailBasicDto.getDealerId());
        if(null != dealerDto || null !=dealerDto.getShortName()){
            List<String> emails = null;
            //邮件
            emails = getEmail(RiskEmailTypeEnum.ORDER_DEALER_REJECTION_PAYMENT); // getRiskEmailList(RiskEmailEnum.ONE.getValue());
            if(null != emails){
                EmailUtil.sendMail(EMAIL_ACCOUNT, EMAIL_PASSWORD,
                        EmailSubjectEnum.BUSINESS_DEALER_REJECTION.getName(),
                        EmailTemplateEnum.BUSINESS_DEALER_REJECTION.getTemplate()
                                .replace("$【name】", dealerDto.getShortName())
                                .replace("$【orderCode】", String.valueOf(orderCode))
                                .replace("$【licencePlate】", carDto.getLicencePlate()),
                        emails);
            }else{
                logger.error("拒收车辆 未配置发送邮件人员的邮箱信息");
            }
        }

        // 钉钉
        DingTalkUtil.execute( ORDER_DEALER_CHANGE_URL,
                EmailTemplateEnum.BUSINESS_DEALER_REJECTION.getTemplate()
                        .replace("$【name】", dealerDto.getShortName())
                        .replace("$【orderCode】", String.valueOf(orderCode))
                        .replace("$【licencePlate】", carDto.getLicencePlate()));
        return ret;
    }

    @Override
    public Boolean orderDealerCarChange(OrderDealerCarChangeVinModifyVo orderDealerCarChangeVinModifyVo) throws Exception {
        //查询账号是否存在
        UserEntity currentLoginUser = tokenUtil.getUser();
        if(null == currentLoginUser){
            throw new Exception("用户未登录");
        }
        CarDto carDto =  carService.getCarByVin(orderDealerCarChangeVinModifyVo.getNewVin());
        if(null == carDto){
            return false;
        }
        Integer newCarId = carDto.getId();
        // 校验新车是否在库  调库存服务  入参：车辆id    出参：true/false

        Boolean flag = stockCarService.getStockCarExist(carDto.getId());
        if(!flag){
            return false;
        }
        if(!carDto.getStatus().equals(CarsOperateStatusEnum.FOR_RENT.getValue())){
            return false;
        }
        Boolean carIdCheck = orderDealerDeliveryService.carIdCheck(carDto.getId());
        if(!carIdCheck){
            return false;
        }

        //旧车绑定中转库
        createBindingFence(orderDealerCarChangeVinModifyVo.getOldStockFenceId(),orderDealerCarChangeVinModifyVo.getOldVin());


        /**
         * 旧车辆回库 调库存服务
         * 入参：old（车辆id） ,
         *       NEW(新车辆id，旧车辆id，旧车辆回到围栏id，中转库id)
         * 出参：true/false
        */
        StockCarRejectionBizModifyDto stockCarBizModifyDto = new StockCarRejectionBizModifyDto();
        stockCarBizModifyDto.setOldCarId(orderDealerCarChangeVinModifyVo.getOldCarId());
        stockCarBizModifyDto.setNewCarId(carDto.getId());
        stockCarBizModifyDto.setFenceId(orderDealerCarChangeVinModifyVo.getOldStockFenceId());
        stockCarBizModifyDto.setStockId(orderDealerCarChangeVinModifyVo.getOldStockId());
        stockCarBizModifyDto.setStorageTime(LocalDateTime.now());
        // 获取登录用户信息  操作人id，操作人名称
        stockCarBizModifyDto.setAccountId(currentLoginUser.getAccountId());
        stockCarBizModifyDto.setAccountAccount(currentLoginUser.getRealName());
        Boolean modifyRejectionStock = stockCarBizService.modifyRejectionStock(stockCarBizModifyDto);
        if(!modifyRejectionStock){
            throw new Exception("车辆回库");
        }

        Long orderCode = orderDealerCarChangeVinModifyVo.getOrderCode();
        Integer oldCarId = orderDealerCarChangeVinModifyVo.getOldCarId();
        //查询旧车辆信息
        OrderDealerDeliveryDto  oldOrderDealerDeliveryDto = orderDealerDeliveryService.getOrderDealerDeliveryInfo(orderCode,oldCarId);
        if(null == oldOrderDealerDeliveryDto){
            throw new Exception("非法入参");
        }

        //将新车辆信息插入订单关联的车辆表
        List<OrderDealerDeliveryCreateDto> newOrderDealerDeliveryList = new ArrayList<>();
        OrderDealerDeliveryCreateDto newOrderDealerDelivery = new OrderDealerDeliveryCreateDto();

        BeanUtils.copyProperties(oldOrderDealerDeliveryDto,newOrderDealerDelivery);
        newOrderDealerDelivery.setCarId(newCarId);
        newOrderDealerDelivery.setSendStatus(OrderDealerSendCarStatusEnum.NO_SEND.getValue());
        newOrderDealerDelivery.setGmtModified(LocalDateTime.now());
        newOrderDealerDeliveryList.add(newOrderDealerDelivery);
        List<Integer> ids = orderDealerDeliveryService.createOrderDealerDelivery(newOrderDealerDeliveryList);
        if(null == ids || ids.size() <= 0){
            throw new Exception("车辆表新增失败");
        }
        //新增更换车辆历史表信息
        OrderDealerChangeCarsLogCreateDto orderDealerChangeCarsLogCreateDto = new OrderDealerChangeCarsLogCreateDto();
        orderDealerChangeCarsLogCreateDto.setOrderCode(orderCode);
        orderDealerChangeCarsLogCreateDto.setOrderDealerCarsId(ids.get(0));
        orderDealerChangeCarsLogCreateDto.setPreviousCarId(oldCarId);
        orderDealerChangeCarsLogService.createChangeCarsLog(orderDealerChangeCarsLogCreateDto);

        //将旧车辆状态改为已更换
        orderDealerDeliveryService.modifyCarChangeStatus(orderCode,oldCarId);

        //查询订单信息
        OrderDealerDetailBasicDto orderDealerDetailBasicDto = orderDealerService.getDetailBasic(orderCode);

        //查询经销商简称
        DealerDto dealerDto = dealerService.getDealerById(orderDealerDetailBasicDto.getDealerId());
        if(null != dealerDto || null !=dealerDto.getShortName()){
            List<String> emails = null;
            //邮件
            emails = getEmail(RiskEmailTypeEnum.ORDER_DEALER_VEHICLE_TO_REPLACED); // getRiskEmailList(RiskEmailEnum.ONE.getValue());
            if(null != emails){
                EmailUtil.sendMail(EMAIL_ACCOUNT, EMAIL_PASSWORD,
                        EmailSubjectEnum.BUSINESS_ORDER_AUDIT_PASS.getName()
                                .replace("$【name】", dealerDto.getShortName()),
                        EmailTemplateEnum.BUSINESS_ORDER_REJECTION.getTemplate()
                                .replace("$【name】", dealerDto.getShortName())
                                .replace("$【orderCode】", String.valueOf(orderCode)),
                        emails);
            }else{
                logger.error("更换拒收车辆 未配置发送邮件人员的邮箱信息");
            }
        }

        // 钉钉
        DingTalkUtil.execute( ORDER_DEALER_CHANGE_URL,
                EmailTemplateEnum.BUSINESS_ORDER_REJECTION.getTemplate()
                        .replace("$【name】", dealerDto.getShortName())
                        .replace("$【orderCode】", String.valueOf(orderCode)));

        return true;
    }

    @Override
    public Boolean modifyDeliverySlip(OrderDeliverySlipModifyVo orderDeliverySlipModifyVo) throws Exception {
        //查询账号是否存在
        UserEntity currentLoginUser = tokenUtil.getUser();
        if(null == currentLoginUser){
            throw new Exception("用户未登录");
        }
        //保存交车单-将车辆状态改为已收车
        DeliverySlipModifyDto deliverySlipModifyDto = new DeliverySlipModifyDto();
        deliverySlipModifyDto.setOrderCode(orderDeliverySlipModifyVo.getOrderCode());
        deliverySlipModifyDto.setCarId(orderDeliverySlipModifyVo.getCarId());
        deliverySlipModifyDto.setDeliveryUrl(orderDeliverySlipModifyVo.getDeliveryUrl());
		// 获取当前已行驶里程-实际里程
		Integer mileage = iovCarService.getOdoMileage(orderDeliverySlipModifyVo.getVin());
		if (mileage == null) {
            throw new Exception("获取当前已行驶里程失败");
        }
		deliverySlipModifyDto.setDrivingMileage(mileage);

        Boolean ret = orderDealerDeliveryService.modifyDeliverySlip(deliverySlipModifyDto);
        if(!ret){
            throw new Exception("收车失败");
        }
        //车辆入库
        StockCarBizModifyDto stockCarBizModifyDto = new StockCarBizModifyDto();
        stockCarBizModifyDto.setCarId(orderDeliverySlipModifyVo.getCarId());
        stockCarBizModifyDto.setStorageTime(LocalDateTime.now());
        stockCarBizModifyDto.setPdiUrl(orderDeliverySlipModifyVo.getDeliveryUrl());
        // 获取登录用户信息  操作人id，操作人名称
        stockCarBizModifyDto.setAccountId(currentLoginUser.getAccountId());
        stockCarBizModifyDto.setAccountAccount(currentLoginUser.getRealName());
        Boolean flag = stockCarBizService.modifyCollectStoreStock(stockCarBizModifyDto);
        if(!flag){
            throw new Exception("收车失败");
        }

        OrderDealerDeliveryDto orderDealerDeliveryDto = orderDealerDeliveryService.getOrderDealerDeliveryInfo(orderDeliverySlipModifyVo.getOrderCode(), orderDeliverySlipModifyVo.getCarId());
        if(null == orderDealerDeliveryDto){
            throw new Exception("非法入参");
        }
        StockStoreDto stockStoreDto = stockStoreService.getStockStoreByStoreId(orderDealerDeliveryDto.getStoreId());
        if(null == stockStoreDto ){
            throw new Exception("库存id为空");
        }
        //维护车辆表 车辆所在仓库
        carService.modifyStockIdById(orderDeliverySlipModifyVo.getCarId(),stockStoreDto.getStockId(),StockCarStockTypeEnum.STORE.getValue());

        //查询订单下所有发车状态
        List<Integer> sendStatusList =  orderDealerDeliveryService.getSendStatusByOrderCode(orderDeliverySlipModifyVo.getOrderCode());
        if(null == sendStatusList || sendStatusList.size() <= 0){
            throw new Exception("非法入参");
        }
        int count = 0;
        for (Integer sendStatus: sendStatusList) {
            if(sendStatus != OrderDealerSendCarStatusEnum.RECEIVED.getValue()){
                count++;
                continue;
            }
        }

        //如果该订单下所有车辆的收车状态都为已收车时，将订单状态改为 完成采购
        if(count == 0){
            Boolean modifyOrderStatus = orderDealerService.modifyOrderStatus(orderDeliverySlipModifyVo.getOrderCode(), OrderDealerStatusEnum.COMPLETE.getValue());
            OrderStatusFlowCreateDto orderStatusFlowCreateDto= new OrderStatusFlowCreateDto();
            orderStatusFlowCreateDto.setOrderCode(orderDeliverySlipModifyVo.getOrderCode());
            orderStatusFlowCreateDto.setOrderStatus(OrderDealerStatusEnum.COMPLETE.getValue());
            //获取登录用户信息  操作人id，操作人名称，操作人类型，
            orderStatusFlowCreateDto.setOrderUserId(currentLoginUser.getAccountId());
            orderStatusFlowCreateDto.setOrderModifiedType(currentLoginUser.getSystemType().getValue());
            orderStatusFlowCreateDto.setOrderUserName(currentLoginUser.getRealName());
            //订单流转状态插入
            Boolean createOrderStatusFlow =orderStatusFlowService.createOrderStatusFlow(orderStatusFlowCreateDto);
            if(!modifyOrderStatus || !createOrderStatusFlow){
                return false;
            }
        }

        //绑定门店围栏
        StockCarDto stockCarDto = getStockCarDto(orderDeliverySlipModifyVo.getCarId());
        createBindingFence(stockCarDto.getFenceId(),orderDeliverySlipModifyVo.getVin());
        return true;
    }

    @Override
    public Boolean orderDealerCreate(OrderDealerCreateVo orderDealerCreateVo) throws Exception {
//查询账号是否存在
        UserEntity currentLoginUser = tokenUtil.getUser();
        if(null == currentLoginUser){
            throw new Exception("用户未登录");
        }

        if(null == orderDealerCreateVo || null == orderDealerCreateVo.getOrderDealerDeliveryCreateVoList() || orderDealerCreateVo.getOrderDealerDeliveryCreateVoList().size() <= 0){
            throw new Exception("非法入参");
        }
        //是否有重复carid
        Long disCount = orderDealerCreateVo.getOrderDealerDeliveryCreateVoList().stream().filter(distinctByKey(OrderDealerDeliveryCreateVo::getCarId)).distinct().count();
        boolean isRepeat = disCount < orderDealerCreateVo.getOrderDealerDeliveryCreateVoList().size();
        if(isRepeat){
            throw new Exception("请输入正确的车架号");
        }


        Long orderCode = Long.valueOf(SnowflakeUtil.getId());;

        //总租金
        BigDecimal sumRent = new BigDecimal("0");
        //总保证金
        BigDecimal sumDeposit = new BigDecimal("0");
        //总期数
        Integer totalPeriods = null;
        //总期数（租期/付款周期）
        if(0 == orderDealerCreateVo.getPaymentCycle()){
            //全款只有一期
            totalPeriods = 1;
        }else {
            totalPeriods = orderDealerCreateVo.getTenancy()/orderDealerCreateVo.getPaymentCycle();
        }
        BigDecimal totalPeriodsBD = new BigDecimal(totalPeriods);

        //新增车辆信息
        List<OrderDealerDeliveryCreateDto> deliveryCreateDtoList= new ArrayList<>();
        OrderDealerDeliveryCreateDto orderDealerDeliveryCreateDto =null;
        for (OrderDealerDeliveryCreateVo orderDealerDeliveryCreateVo:orderDealerCreateVo.getOrderDealerDeliveryCreateVoList()) {
            orderDealerDeliveryCreateDto = new OrderDealerDeliveryCreateDto();
            //车辆校验

            CarDto carDto =  carService.getCarById(orderDealerDeliveryCreateVo.getCarId());
            if(null == carDto){
                throw new Exception("无车辆信息");
            }
            if(!carDto.getStatus().equals(CarsOperateStatusEnum.FOR_RENT.getValue())){
                throw new Exception("该车辆不在运营状态");
            }
            // 判断车辆是否在库
            Boolean flag = stockCarService.getStockCarExist(carDto.getId());
            if(!flag){
                throw new Exception("车辆不在库");
            }
            Boolean carIdCheck = orderDealerDeliveryService.carIdCheck(carDto.getId());
            if(!carIdCheck){
                throw new Exception("车辆已锁定");
            }
            BeanUtils.copyProperties(orderDealerDeliveryCreateVo, orderDealerDeliveryCreateDto);
            orderDealerDeliveryCreateDto.setOrderCode(orderCode);
            orderDealerDeliveryCreateDto.setSendStatus(OrderDealerSendCarStatusEnum.NO_SEND.getValue());
            //未更换
            orderDealerDeliveryCreateDto.setIsChanged(false);
            //已锁定
            orderDealerDeliveryCreateDto.setIsLock(false);
            if(null != orderDealerDeliveryCreateVo.getRent()){
                sumRent = sumRent.add(orderDealerDeliveryCreateVo.getRent().multiply(totalPeriodsBD));
            }
            if(null!= orderDealerDeliveryCreateVo.getDeposit()){
                sumDeposit = sumDeposit.add(orderDealerDeliveryCreateVo.getDeposit());
            }
            deliveryCreateDtoList.add(orderDealerDeliveryCreateDto);
        }

        //保存合同信息
        ContractPurchaseBizCreateDto contractPurchaseBizCreateDto = new ContractPurchaseBizCreateDto();
        contractPurchaseBizCreateDto.setContractCode(orderDealerCreateVo.getContractNo());
        contractPurchaseBizCreateDto.setOrderCode(orderCode);
        if(StringUtils.isNotBlank(orderDealerCreateVo.getContractSignDateStr())){
            contractPurchaseBizCreateDto.setSignedTime(ObjectCastUtil.getDayStart(orderDealerCreateVo.getContractSignDateStr()));
        }
        List<ContractImageBizCreateDto> list = new ArrayList<>();
        ContractImageBizCreateDto contractImageBizCreateDto= null ;
        for (ContractPathVo contractPathVo:orderDealerCreateVo.getContractList()) {
            contractImageBizCreateDto = new ContractImageBizCreateDto();
            contractImageBizCreateDto.setName(contractPathVo.getContractName());
            contractImageBizCreateDto.setPath(contractPathVo.getContractUrl());
            list.add(contractImageBizCreateDto);
        }
        contractPurchaseBizCreateDto.setList(list);
        contractBizService.createPurchaseContract(contractPurchaseBizCreateDto);

        List<Integer> ids = orderDealerDeliveryService.createOrderDealerDelivery(deliveryCreateDtoList);

        //新增还款计划
        OrderScheduleDealerCreateDto orderScheduleDealerCreateDto = new OrderScheduleDealerCreateDto();
        orderScheduleDealerCreateDto.setOrderCode(orderCode);
        orderScheduleDealerCreateDto.setDealerId(orderDealerCreateVo.getDealerId());
        if(StringUtils.isNotBlank(orderDealerCreateVo.getStartLeaseDateStr())){
            orderScheduleDealerCreateDto.setStartLeaseDate(ObjectCastUtil.getDayStart(orderDealerCreateVo.getStartLeaseDateStr()));
        }
        orderScheduleDealerCreateDto.setRepayDate(orderDealerCreateVo.getRepayDate());
        orderScheduleDealerCreateDto.setPaymentCycle(orderDealerCreateVo.getPaymentCycle());
        orderScheduleDealerCreateDto.setTotalPeriods(totalPeriods);
        orderScheduleDealerCreateDto.setRent(sumRent);
        orderScheduleDealerCreateDto.setDeposit(sumDeposit);
        orderScheduleService.createDealerOrderSchedule(orderScheduleDealerCreateDto);

        //新增订单主表
        OrderCreateDto createDto = new OrderCreateDto();
        createDto.setType(OrderTypeEnum.DEALER);
        createDto.setOrderCode(orderCode);
        orderService.create(createDto);


        //新增采购单
        OrderDealerCreateDto orderDealerCreateDto = new OrderDealerCreateDto();
        BeanUtils.copyProperties(orderDealerCreateVo,orderDealerCreateDto);
        orderDealerCreateDto.setOrderCode(orderCode);
        orderDealerCreateDto.setOrderStatus(OrderDealerStatusEnum.PREPAID_DOWN_PAYMENT.getValue());
        orderDealerCreateDto.setRentNumbers(orderDealerCreateVo.getOrderDealerDeliveryCreateVoList().size());
        orderDealerCreateDto.setRentAmount(sumRent);
        orderDealerCreateDto.setDepositAmount(sumDeposit);
        orderDealerCreateDto.setTotalPeriods(totalPeriods);
        if(StringUtils.isNotBlank(orderDealerCreateVo.getStartLeaseDateStr())){
            orderDealerCreateDto.setStartLeaseDate(ObjectCastUtil.getDayStart(orderDealerCreateVo.getStartLeaseDateStr()));
        }
        if(StringUtils.isNotBlank(orderDealerCreateVo.getContractSignDateStr())){
            orderDealerCreateDto.setContractSignDate(ObjectCastUtil.getDayStart(orderDealerCreateVo.getContractSignDateStr()));
        }
        orderDealerService.createOrderDealer(orderDealerCreateDto);


        //新增流转订单流转状态
        OrderStatusFlowCreateDto orderStatusFlowCreateDto = new OrderStatusFlowCreateDto();
        orderStatusFlowCreateDto.setOrderCode(orderCode);
        //获取登录用户信息  操作人id，操作人名称，操作人类型，
        orderStatusFlowCreateDto.setOrderUserId(currentLoginUser.getAccountId());
        orderStatusFlowCreateDto.setOrderModifiedType(currentLoginUser.getSystemType().getValue());
        orderStatusFlowCreateDto.setOrderUserName(currentLoginUser.getRealName());

        orderStatusFlowCreateDto.setOrderStatus(OrderDealerStatusEnum.CREATE_ORDER.getValue());
        orderStatusFlowService.createOrderStatusFlow(orderStatusFlowCreateDto);
        orderStatusFlowCreateDto.setOrderStatus(OrderDealerStatusEnum.PREPAID_DOWN_PAYMENT.getValue());
        orderStatusFlowService.createOrderStatusFlow(orderStatusFlowCreateDto);


        return true;
    }

    @Override
    public Boolean contractCodeRepeat(String contractCode) throws Exception {
        Boolean flag = orderDealerService.getContractNo(contractCode);
        if(flag){
            throw new Exception("合同编号已存在");
        }
        return !flag;
    }

    @Override
    public OrderDealerCarInfoVo carInfoRepeat(Integer vehicleId, String vin) throws Exception {
        OrderDealerCarInfoVo orderDealerCarInfoVo= null;
        CarDto carDto =  carService.getCarByVin(vin);
        if(null == carDto){
            return orderDealerCarInfoVo;
        }
        if(!vehicleId.equals(carDto.getVehicleId())){
            return orderDealerCarInfoVo;
        }
        if(!carDto.getStatus().equals(CarsOperateStatusEnum.FOR_RENT.getValue())){
            return orderDealerCarInfoVo;
        }
        // 判断车辆是否在库
        Boolean flag = stockCarService.getStockCarExist(carDto.getId());
        if(!flag){
            return orderDealerCarInfoVo;
        }
        orderDealerCarInfoVo= new OrderDealerCarInfoVo();
        orderDealerCarInfoVo.setCarId(carDto.getId());
        orderDealerCarInfoVo.setCarType(CarsTypeEnum.getName(carDto.getVehicleType()));
        orderDealerCarInfoVo.setLicencePlate(carDto.getLicencePlate());

		// 获取当前已行驶里程-实际里程
		Integer mileage = iovCarService.getOdoMileage(carDto.getVin());
		if (mileage == null) {
            throw new Exception("获取当前已行驶里程失败");
        }

		orderDealerCarInfoVo.setDrivingMileage(mileage + "");

        return orderDealerCarInfoVo;
    }

    @Override
    public OrderDealerDetailBasicInfoVo getDetailBasic(Long orderCode) throws Exception {
        OrderDealerDetailBasicInfoVo orderDealerDetailBasicVo = null;

        OrderDealerDetailBasicBizDto orderDealerDetailBasicDto = orderScheduleBizService.getOrderDealerDetailBasicBizDto(orderCode);
        if(null == orderDealerDetailBasicDto){
            throw new Exception("非法入参");
        }
        orderDealerDetailBasicVo = new OrderDealerDetailBasicInfoVo();
        BeanUtils.copyProperties(orderDealerDetailBasicDto, orderDealerDetailBasicVo);

        //获取经销商名称
        DealerDto dealerDto = dealerService.getDealerById(orderDealerDetailBasicDto.getDealerId());
        if(null == dealerDto){
            throw new Exception("无经销商名称信息");
        }
        orderDealerDetailBasicVo.setDealerName(dealerDto.getShortName());
        //获取联系人信息
        DealerDetailDto dealerDetailDto = dealerDetailService.getDealerDetailById(orderDealerDetailBasicDto.getDealerId());
        if(null == dealerDetailDto){
            throw new Exception("无联系人信息");
        }
        orderDealerDetailBasicVo.setContact(dealerDetailDto.getResponsibleName());
        orderDealerDetailBasicVo.setContactNumber(dealerDetailDto.getResponsiblePhone());

        return orderDealerDetailBasicVo;
    }

    @Override
    public List<OrderDealerDetailScheduleVo> orderSchedulePlan(Long orderCode) throws Exception {
        List<OrderDealerDetailScheduleVo> orderDealerDetailScheduleVoList = null;
        List<OrderScheduleDto> orderScheduleDtoList = orderScheduleService.getOrderSchedule(orderCode);
        if (null == orderScheduleDtoList || orderScheduleDtoList.size() <= 0) {
            throw new Exception("非法入参");
        }
        orderDealerDetailScheduleVoList = new ArrayList<>();
        OrderDealerDetailScheduleVo orderDealerDetailScheduleVo = null;
        Integer overdueDays = null;
        for (OrderScheduleDto orderScheduleDto : orderScheduleDtoList) {
            orderDealerDetailScheduleVo = new OrderDealerDetailScheduleVo();
            BeanUtils.copyProperties(orderScheduleDto,orderDealerDetailScheduleVo);
            orderDealerDetailScheduleVo.setStatus(orderScheduleDto.getStatus().getValue());
            orderDealerDetailScheduleVo.setStatusName(orderScheduleDto.getStatus().getName());
            // 获取审核状态
            OfflineBizDto offlineBizDto = offlineBizService.getOffline(orderScheduleDto.getOrderCode(),orderScheduleDto.getId());
            if (null != offlineBizDto ) {
                orderDealerDetailScheduleVo.setAuditStatus(OfflineAuditStatusEnum.getName(offlineBizDto.getAuditStatus()));
            }
            //如果是第一期，不用处理逾期天数
            if(1 == orderDealerDetailScheduleVo.getPeriods()){
                orderDealerDetailScheduleVo.setPayableDate(null);
                orderDealerDetailScheduleVo.setIsOverdue("否");
                orderDealerDetailScheduleVo.setOverdueDays(0);
                orderDealerDetailScheduleVoList.add(orderDealerDetailScheduleVo);
                continue;
            }else{
                orderDealerDetailScheduleVo.setDeposit(null);
            }

            //计算应还款日小于当前时间的逾期天数
            if(null != orderDealerDetailScheduleVo.getPayableDate()){
                    if(null != orderDealerDetailScheduleVo.getPaySuccessTime()){
                        //实际付款日期-应付款日期
                        overdueDays = (int)DateUtil.getDaysDiff(orderDealerDetailScheduleVo.getPayableDate() ,orderDealerDetailScheduleVo.getPaySuccessTime());
                        if(overdueDays <= 0 ){
                            orderDealerDetailScheduleVo.setIsOverdue(OrderDealerScheduleOverdueEnum.NO_OVERDUE.getName());
                            orderDealerDetailScheduleVo.setOverdueDays(0);
                        }else{
                            orderDealerDetailScheduleVo.setIsOverdue(OrderDealerScheduleOverdueEnum.OVERDUE.getName());
                            orderDealerDetailScheduleVo.setOverdueDays(overdueDays);
                        }
                    }else {
                        //实际付款日期-应付款日期
                        overdueDays = (int)DateUtil.getDaysDiff(orderDealerDetailScheduleVo.getPayableDate() ,LocalDateTime.now());
                        if(overdueDays > 0 ){
                            orderDealerDetailScheduleVo.setIsOverdue(OrderDealerScheduleOverdueEnum.OVERDUE.getName());
                            orderDealerDetailScheduleVo.setOverdueDays(overdueDays);
                        }
                    }
            }
            orderDealerDetailScheduleVoList.add(orderDealerDetailScheduleVo);



        }

        return orderDealerDetailScheduleVoList;
    }

    @Override
    public List<OrderDealerDetailScheduleVo> orderScheduleExpire(Long orderCode) throws Exception {
        List<OrderDealerDetailScheduleVo> orderDealerDetailScheduleVoList = null;
        List<OrderScheduleDto> orderScheduleDtoList = orderScheduleService.getOrderSchedule(orderCode);
        if (null == orderScheduleDtoList || orderScheduleDtoList.size() <= 0) {
            throw new Exception("非法入参");
        }
        orderDealerDetailScheduleVoList = new ArrayList<>();
        OrderDealerDetailScheduleVo orderDealerDetailScheduleVo = null;
        Integer overdueDays = null;
        for (OrderScheduleDto orderScheduleDto : orderScheduleDtoList) {
            if(OrderScheduleStatusEnum.ALREADY.equals(orderScheduleDto.getStatus()) || OrderScheduleStatusEnum.TERMINATION.equals(orderScheduleDto.getStatus())){
                continue;
            }
            orderDealerDetailScheduleVo = new OrderDealerDetailScheduleVo();
            BeanUtils.copyProperties(orderScheduleDto,orderDealerDetailScheduleVo);
            orderDealerDetailScheduleVo.setStatus(orderScheduleDto.getStatus().getValue());
            orderDealerDetailScheduleVo.setStatusName(orderScheduleDto.getStatus().getName());
            // 获取审核状态
            OfflineBizDto offlineBizDto = offlineBizService.getOffline(orderScheduleDto.getOrderCode(),orderScheduleDto.getId());
            if (null != offlineBizDto ) {
                orderDealerDetailScheduleVo.setAuditStatus(OfflineAuditStatusEnum.getName(offlineBizDto.getAuditStatus()));
            }
            //如果是第一期，不用处理逾期天数
            if(1 == orderDealerDetailScheduleVo.getPeriods()){
                orderDealerDetailScheduleVo.setPayableDate(null);
                orderDealerDetailScheduleVo.setIsOverdue("否");
                orderDealerDetailScheduleVo.setOverdueDays(0);
                orderDealerDetailScheduleVoList.add(orderDealerDetailScheduleVo);
                continue;
            }else{
                orderDealerDetailScheduleVo.setDeposit(null);
            }

            //计算应还款日小于当前时间的逾期天数
            if(LocalDate.now().isBefore(orderDealerDetailScheduleVo.getPayableDate())  ||  LocalDate.now().isEqual(orderDealerDetailScheduleVo.getPayableDate())){
                continue;
            }else{
                if(null != orderDealerDetailScheduleVo.getPaySuccessTime()){
                    //实际付款日期-应付款日期
                    overdueDays = (int)DateUtil.getDaysDiff(orderDealerDetailScheduleVo.getPayableDate() ,orderDealerDetailScheduleVo.getPaySuccessTime());
                    if(overdueDays <= 0 ){
                        orderDealerDetailScheduleVo.setIsOverdue(OrderDealerScheduleOverdueEnum.NO_OVERDUE.getName());
                        orderDealerDetailScheduleVo.setOverdueDays(0);
                    }else{
                        orderDealerDetailScheduleVo.setIsOverdue(OrderDealerScheduleOverdueEnum.OVERDUE.getName());
                        orderDealerDetailScheduleVo.setOverdueDays(overdueDays);
                    }
                }else {
                    //实际付款日期-应付款日期
                    overdueDays = (int)DateUtil.getDaysDiff(orderDealerDetailScheduleVo.getPayableDate() ,LocalDateTime.now());
                    if(overdueDays > 0 ){
                        orderDealerDetailScheduleVo.setIsOverdue(OrderDealerScheduleOverdueEnum.OVERDUE.getName());
                        orderDealerDetailScheduleVo.setOverdueDays(overdueDays);
                    }
                }
            }
            orderDealerDetailScheduleVoList.add(orderDealerDetailScheduleVo);



        }

        return orderDealerDetailScheduleVoList;
    }

    @Override
    public List<OrderFuzzyQueryVo> getDealerListByName(String name) throws Exception {
        List<OrderFuzzyQueryVo> orderFuzzyQueryVoList = new ArrayList<>();
        List<DealerDto> dealerDtoList = dealerService.getDealerListByName(name);
        if(null == dealerDtoList  || dealerDtoList.size()<= 0){
            return orderFuzzyQueryVoList;
        }
        OrderFuzzyQueryVo orderFuzzyQueryVo = null;
        for (DealerDto dealerDto:dealerDtoList) {
            orderFuzzyQueryVo = new OrderFuzzyQueryVo();
            orderFuzzyQueryVo.setId(dealerDto.getDealerId());
            orderFuzzyQueryVo.setName(dealerDto.getShortName());
            orderFuzzyQueryVoList.add(orderFuzzyQueryVo);
        }

        return orderFuzzyQueryVoList;
    }

    @Override
    public List<OrderFuzzyQueryVo> getDealerRepaymentListByName(String name) throws Exception {
        List<OrderFuzzyQueryVo> orderFuzzyQueryVoList = new ArrayList<>();
        List<DealerDto> dealerDtoList = dealerService.getDealerListByName(name);
        if(null == dealerDtoList  || dealerDtoList.size()<= 0){
            return orderFuzzyQueryVoList;
        }
        OrderFuzzyQueryVo orderFuzzyQueryVo = null;
        for (DealerDto dealerDto:dealerDtoList) {
            Integer dealerId = orderScheduleService.getDealerByDealerId(dealerDto.getDealerId());
            if(null == dealerId){
                continue;
            }
            orderFuzzyQueryVo = new OrderFuzzyQueryVo();
            orderFuzzyQueryVo.setId(dealerDto.getDealerId());
            orderFuzzyQueryVo.setName(dealerDto.getShortName());
            orderFuzzyQueryVoList.add(orderFuzzyQueryVo);
        }

        return orderFuzzyQueryVoList;
    }

    @Override
    public List<OrderFuzzyQueryVo> getSubcompanyByName(String name) throws Exception {
        List<OrderFuzzyQueryVo> orderFuzzyQueryVoList = new ArrayList<>();
        List<SubcompanyDto> SubcompanyDtoList= subcompanyService.getSubcompanyByName(name);
        if(null == SubcompanyDtoList  || SubcompanyDtoList.size()<= 0){
            return orderFuzzyQueryVoList;
        }
        OrderFuzzyQueryVo orderFuzzyQueryVo = null;
        for (SubcompanyDto subcompanyDto:SubcompanyDtoList) {
            orderFuzzyQueryVo = new OrderFuzzyQueryVo();
            orderFuzzyQueryVo.setId(subcompanyDto.getId());
            orderFuzzyQueryVo.setName(subcompanyDto.getFullName());
            orderFuzzyQueryVoList.add(orderFuzzyQueryVo);
        }

        return orderFuzzyQueryVoList;
    }

    @Override
    public List<OrderScheduleUnpaidVo> getOrderScheduleUnpaid(Integer dealerId) throws Exception {
        List<OrderScheduleUnpaidVo> orderScheduleUnpaidVoList = new ArrayList<>();
        List<OrderScheduleUnpaidDto> orderScheduleUnpaidDtoList = orderScheduleService.getOrderScheduleUnpaidByDealerId(dealerId);
        if(null == orderScheduleUnpaidDtoList || orderScheduleUnpaidDtoList.size() <= 0){
            return orderScheduleUnpaidVoList;
        }
        OrderScheduleUnpaidVo orderScheduleUnpaidVo = null;
        for (OrderScheduleUnpaidDto orderScheduleUnpaidDto:orderScheduleUnpaidDtoList) {
            orderScheduleUnpaidVo = new OrderScheduleUnpaidVo();
            BeanUtils.copyProperties(orderScheduleUnpaidDto,orderScheduleUnpaidVo);
            orderScheduleUnpaidVoList.add(orderScheduleUnpaidVo);
        }
        return orderScheduleUnpaidVoList;
    }



    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
    }


    /**
     * 围栏绑定
     * @param fenceId
     * @param vin
     * @return
     */
    private Boolean createBindingFence(Integer fenceId,String vin) {
        IovFenceBindingCreateDto dto = new IovFenceBindingCreateDto();
        if(null == fenceId || StringUtils.isAllBlank(vin)) {
            return false;
        }
        dto.setFenceId(Long.valueOf(fenceId));
        List<String> list= new ArrayList<>(1);
        list.add(vin);
        dto.setListVin(list);
        try {
            Boolean isOK = iovFenceService.addBindingFence(dto);
            logger.info("围栏绑定isOK返回值："+ isOK);
            return isOK;
        }catch (Exception e) {
            logger.error("围栏绑定异常：",e);
            throw new BizException("车联网车辆绑定门店围栏失败!"+ e);
        }
    }

    /**
     * 解绑围栏
     * @param fenceId
     * @param vin
     * @return
     */
    private Boolean modifyBindingFence(Integer fenceId,String vin) {
        IovFenceBindingModifyDto dto = new IovFenceBindingModifyDto();
        if(null == fenceId || StringUtils.isAllBlank(vin)) {
            return false;
        }
        dto.setFenceId(Long.valueOf(fenceId));
        List<String> list= new ArrayList<>(1);
        list.add(vin);
        dto.setListVin(list);
        try {
            return iovFenceService.modifyBindingFence(dto);
        }catch (Exception e) {
            logger.error("解绑围栏异常：",e);
            return false;
        }
    }


    /**解除仓库围栏
     * @param stockId
     * @param vin
     */
    private void modifyFenceStock(Integer stockId,String vin){
        EntrepotStorageDto entrepotStorage = getEntrepotStorage(stockId);
        Boolean flag = modifyBindingFence(entrepotStorage.getFenceId(), vin);
        if(!flag) {
            throw new BizException("车联网解除仓库围栏失败!");
        }
    }

    /**
     * 车辆绑定门店围栏
     * @param stockId
     * @param vin
     */
    private void createFenceStore(Integer stockId,String vin) {
        StockStoreDto  stockStoreDto = getStockStore(stockId);
        StoreDetailDto store = getStoreDetailById(stockStoreDto.getStoreId());
        Boolean flag = createBindingFence(store.getFenceId(),vin);
        logger.info("围栏绑定flag返回值："+ flag);
        if(!flag) {
            throw new BizException("车联网车辆绑定门店围栏失败!");
        }
    }

    /**
     * 根据中转库id查询中转库信息
     * @param stockId
     * @return
     */
    private EntrepotStorageDto getEntrepotStorage(Integer stockId) {
        EntrepotStorageDto entrepotStorage = entrepotStorageService.getEntrepotStorage(stockId);
        if(null == entrepotStorage) {
            throw new BizException("不存在该中转库信息");
        }
        return entrepotStorage;
    }

    /**
     * 根据门店id获取门店信息
     * @param storeId
     * @return
     */
    private StoreDetailDto getStoreDetailById(Integer storeId) {
        try {
            StoreDetailDto store = storeDetailService.getStoreDetailById(storeId);
            if(null == store) {
                throw new BizException("不存在该门店信息");
            }
            return store;
        } catch (Exception e) {
            logger.error("根据门店id获取门店信息异常：",e);
            throw new BizException("门店服务异常");
        }
    }

    /**
     * 根据车辆id获取库存信息
     * @param carId
     * @return
     */
    private StockCarDto getStockCarDto(Integer carId) {
        StockCarDto stockCarDto = stockCarService.getStockCar(carId);
        if(null == stockCarDto) {
            throw new BizException(101, "不存在该条信息");
        }
        return stockCarDto;
    }


    /**
     * 根据仓库id 查询门店id
     * @param stockId
     * @return
     */
    private StockStoreDto getStockStore(Integer stockId) {
        //根据仓库id 查询门店id
        StockStoreDto stockStore = stockStoreService.getStockStore(stockId);
        if(null == stockStore ) {
            throw new BizException("该仓库没有门店信息");
        }
        return stockStore;
    }


    /**
     * 获取邮件人信息
     * @return
     */
    private List<String> getEmail(RiskEmailTypeEnum riskEmailTypeEnum){
        List<RiskEmailDto> riskList = riskEmailService.getByType(riskEmailTypeEnum.getValue(),RiskEmailReceiveTypeEnum.EMAIL_RECIPIENT.getValue());
        List<String> list=null;
        if(null != riskList && !riskList.isEmpty()) {
            list=new ArrayList<>();
            for (RiskEmailDto dto : riskList) {
                list.add(dto.getEmail());
            }
        }
        return list;
    }
}
